package com.yinian.server.controller;


import cn.hutool.core.img.Img;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.yinian.common.constant.UrlConstant;
import com.yinian.common.properties.JwtProperties;
import com.yinian.common.result.Result;
import com.yinian.pojo.dto.ImageDTO;
import com.yinian.server.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@Slf4j
@Api(tags = "加载图片接口")
public class ImageController {

    public static final Map<String,String> imgMap= new ConcurrentHashMap<>();



    @PostMapping("/image")
    @ApiOperation(value = "返回请求路径图片")
    public Result<String> getImage(@RequestBody ImageDTO imageDTO) throws IOException {
        String imageURL = imageDTO.getImageUrl();
        byte[] imageBytes = Files.readAllBytes(Paths.get(imageURL));
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        return Result.success(base64Image);

    }


    @ApiOperation(value = "上传图片")
    @ApiImplicitParam(name = "file",value = "图片上传",required = true,dataTypeClass = MultipartFile.class,
            allowMultiple = true,paramType = "query")
    @PostMapping(value = "/upload-avatar")
    @ResponseBody
    public String insertOrderImg(@RequestParam("file") MultipartFile file) {
        // 文件上传路径 todo 需要修改
//        String location = "E:\\image\\";
        String location = "\\usr\\image\\avatar\\";

        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //设置允许上传文件类型
        String suffixList = ".jpg,.png,.ico,.bmp,.jpeg";
        String imgUrl=null;
        // 判断是否包含
        if (suffixList.contains(extName.trim().toLowerCase())) {
            // 保存文件的路径
            String path = location + originalFilename;
            //  spring的transferTo保存文件方法
            try {
                file.transferTo(new File(path));
                imgUrl = UrlConstant.imageUrl + originalFilename;
            } catch (IOException e) {
                log.info("保存失败");
            }
        }
        return imgUrl;
    }


//
//    @ApiOperation(value = "上传图片")
//    @ApiImplicitParam(name = "file",value = "图片上传",required = true,dataTypeClass = MultipartFile.class,
//            allowMultiple = true,paramType = "query")
//    @PostMapping(value = "/upload")
//    @ResponseBody
//    public String insertOrderImg(@RequestParam("file") MultipartFile file) throws IOException {
//        // 文件上传路径
//        String location = "E:\\image\\";
//        String originalFilename = file.getOriginalFilename();
//        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
//        //设置允许上传文件类型
//        String suffixList = ".jpg,.png,.ico,.bmp,.jpeg";
//        String imgUrl=null;
//        // 判断是否包含
//        if (suffixList.contains(extName.trim().toLowerCase())) {
//            BufferedImage image = ImgUtil.read(file.getInputStream());
//            int height = image.getHeight();
//            int width = image.getWidth();
//            // 保存文件的路径
//            String path = location + originalFilename;
//            // thumbnailator压缩存放路径
//            String thumbPath= location+"thumbnailator"+originalFilename;
//            //Img压缩存放路径
//            String imgPath = location +"img"+ originalFilename;
//            String newPath = location +"new"+ originalFilename;
//            //同一文件SHA256进行哈希运算后值唯一
//            String shaValue = DigestUtil.sha256Hex(file.getBytes());
//            if (imgMap.containsKey(shaValue)) {
//                log.info("重复的SHA{},已上传的文件名{}",shaValue,imgMap.get(shaValue));
//                return re"已经上传,不可重复";
//            }
//            imgMap.put(shaValue,originalFilename);
//            //  spring的transferTo保存文件方法
//            try {
//                log.info("原图高{},宽{},大小{}KB",height,width,file.getSize()/1024);
//                file.transferTo(new File(path));
//
//                //Hutool图像编辑器压缩
//                Img img = Img.from(file.getInputStream());
//                Image img1 = img.scale(0.5f).setQuality(0.2f).getImg();
//                byte[] bytes = ImgUtil.toBytes(img1, ImgUtil.IMAGE_TYPE_JPEG);
//                log.info("Hutool压缩后高{},宽{},大小{}KB",img1.getHeight(null),img1.getWidth(null),bytes.length/1024);
//                FileUtil.writeBytes(bytes,imgPath);
//
//                //Thumbnails压缩 要读取压缩后图片大小和尺寸必须写后再读，没有Img编辑器压缩方便
//                OutputStream outputStream1 = new FileOutputStream(thumbPath);
//                Thumbnails.of(file.getInputStream())
//                        .scale(0.5f)
//                        .outputQuality(0.2f)
//                        .toOutputStream(outputStream1);
//                outputStream1.close();
//                byte[] bytes1 = FileUtil.readBytes(thumbPath);
//                BufferedImage read1 = ImgUtil.read(thumbPath);
//                log.info("Thumbnails压缩高{},宽{},大小{}KB",read1.getHeight(),read1.getWidth(),bytes1.length/1024);
//
////                //Hutool另一种压缩方法，要读取压缩后图片大小和尺寸必须写后再读 ，没有Img编辑器压缩方便
////                OutputStream outputStream2 = new FileOutputStream(newPath);
////                ImageOutputStream imageOutputStream = ImgUtil.getImageOutputStream(outputStream2);
////                ImgUtil.scale(image, imageOutputStream, 0.5f);
////                ImgUtil.write(image,ImgUtil.IMAGE_TYPE_JPG,imageOutputStream,0.2F);
////                outputStream2.close();
////                byte[] bytes2 = FileUtil.readBytes(newPath);
////                BufferedImage read2 = ImgUtil.read(newPath);
////                log.info("Hutool直接压缩高{},宽{},大小{}KB",read2.getHeight(),read2.getWidth(),bytes2.length/1024);
//                imgUrl = host + originalFilename;
//            } catch (IOException e) {
//                log.info("保存失败");
//            }
//        }
//        return imgUrl;
//    }


}
